package com.prp.util.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.smtp.SMTPTransport;

public class MailSender {
	private String username;
	private String password;
	private String sendHost;
	private String sendProtocol;
	private boolean useSSL;

	private Session session;

	public MailSender(String username, String password, String sendHost,
			String sendProtocol, boolean useSSL) {
		this.username = username;
		this.password = password;
		this.sendHost = sendHost;
		this.sendProtocol = sendProtocol;
		this.useSSL = useSSL;
		
		init();
	}

	private void init() {
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", sendProtocol);
		props.setProperty("mail.smtp.class", SMTPTransport.class.getName());
		props.setProperty("mail.smtp.host", sendHost);
		props.setProperty("mail.smtp.auth", "true");
		if (useSSL) {
			props.setProperty("mail.smtp.socketFactory.class",
					"javax.net.ssl.SSLSocketFactory");
			props.setProperty("mail.smtp.socketFactory.fallback", "false");
			props.setProperty("mail.smtp.port", "465");
			props.setProperty("mail.smtp.socketFactory.port", "465");
		}

		MailAuthenticator authenticator = new MailAuthenticator(username,
				password);
		session = Session.getDefaultInstance(props, authenticator);
		session.setDebug(true);
	}

	public void sendMail(String fromAddr, String toAddr, String msgContent,
			String subject) throws Exception {
		Message msg = createSimpleMessage(fromAddr, toAddr, msgContent, subject);
		Transport.send(msg);
	}

	private Message createSimpleMessage(String fromAddr, String toAddr,
			String msgContent, String subject) throws Exception {
		// TODO Auto-generated method stub
		Message msg = new MimeMessage(session);

		InternetAddress[] toAddrs = InternetAddress.parseHeader(toAddr, false);
		msg.setRecipients(Message.RecipientType.TO, toAddrs);
		msg.setSentDate(new java.util.Date());
		msg.setSubject(subject);
		msg.setFrom(new InternetAddress(fromAddr));
		msg.setContent(msgContent,"text/html;charset=utf8");

		return msg;
	}
}
